<?php

namespace App\Admin\Actions;

use App\Library\Logic\AmountLogic;
use App\Library\Logic\OperateLogLogic;
use App\Models\AdjustmentModel;
use App\Models\AmountModel;
use Encore\Admin\Actions\Response;
use Encore\Admin\Actions\RowAction;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;

class AdjustmentAction extends RowAction
{
    public $name = '调账';

    /**
     * handle
     * @param AmountModel $model
     * @param Request $request
     * @return Response
     */
    public function handle(AmountModel $model, Request $request): Response
    {
        if (!preg_match(__('com.priceReg'), $request->amount)) {
            return $this->response()->error('金额格式错误')->refresh();
        } else if ($request->password !== config('app.adjustmentPassword')) {
            return $this->response()->error('密码错误')->refresh();
        }
        $adjustment = AdjustmentModel::insertForModel([
            'type' => $request->type,
            'userId' => $model->user_id,
            'amount' => (float)$request->amount,
            'description' => $request->description,
            'operateId' => Admin::user()->user_id,
        ]);
        AmountLogic::insertForModelOfLock([
            'type' => 'adjustment',
            'userId' => $adjustment->user_id,
            'title' => '手动调账',
            'object_type' => 'adjustment',
            'object_id' => $adjustment->id,
            'amount' => (int)$request->addOrSub === 0 ? $adjustment->amount : -$adjustment->amount,
            'description' => $adjustment->description,
        ]);
        OperateLogLogic::add(Admin::user()->user_id, 'admin.amount.adjust');
        return $this->response()->success('操作成功')->refresh();
    }

    /**
     * form
     * @return void
     */
    public function form(): void
    {
        $this->password('password', '密码')->attribute('maxlength', 10)->required();
        $this->select('type', '类型')->options([0 => '手动调账'])->required();
        $this->text('amount', '金额')->required()->attribute('maxlength', 10)->default(0);
        $this->select('addOrSub', '加减')->options([0 => '加', 1 => '减'])->default(0)->required();
        $this->text('description', '描述')->attribute('maxlength', 255)->required();
    }
}
